<template>
  <div class="p-6 space-y-6">
    <!-- 见面倒计时 - 大卡片 -->
    <div class="glass-effect rounded-3xl p-8 shadow-pink-xl text-center relative overflow-hidden">
      <!-- 背景装饰 -->
      <div class="absolute top-0 right-0 text-9xl opacity-10">💑</div>

      <h2 class="text-2xl font-bold text-pink-600 mb-4">下次见面倒计时</h2>
      <div class="flex items-center justify-center gap-4 mb-4">
        <div class="flex flex-col items-center">
          <span class="text-5xl font-bold text-pink-500">{{ countdown.days }}</span>
          <span class="text-sm text-pink-400 mt-1">天</span>
        </div>
        <span class="text-3xl text-pink-300">:</span>
        <div class="flex flex-col items-center">
          <span class="text-5xl font-bold text-pink-500">{{ countdown.hours }}</span>
          <span class="text-sm text-pink-400 mt-1">时</span>
        </div>
        <span class="text-3xl text-pink-300">:</span>
        <div class="flex flex-col items-center">
          <span class="text-5xl font-bold text-pink-500">{{ countdown.minutes }}</span>
          <span class="text-sm text-pink-400 mt-1">分</span>
        </div>
      </div>
      <p class="text-pink-400">{{ countdown.targetDate }} · {{ countdown.description }}</p>
    </div>

    <!-- 恋爱统计面板 -->
    <div class="glass-effect rounded-2xl p-6 shadow-pink-md">
      <h3 class="text-xl font-bold text-pink-600 mb-4 flex items-center gap-2">
        <span>📊</span>
        <span>恋爱统计</span>
      </h3>
      <div class="grid grid-cols-3 gap-4">
        <div class="text-center">
          <p class="text-3xl font-bold text-pink-500">{{ stats.days }}</p>
          <p class="text-sm text-pink-400 mt-1">在一起天数</p>
        </div>
        <div class="text-center">
          <p class="text-3xl font-bold text-pink-500">{{ stats.meetings }}</p>
          <p class="text-sm text-pink-400 mt-1">见面次数</p>
        </div>
        <div class="text-center">
          <p class="text-3xl font-bold text-pink-500">{{ stats.messages }}</p>
          <p class="text-sm text-pink-400 mt-1">互动次数</p>
        </div>
      </div>
    </div>

    <!-- 全部日程 -->
    <div class="glass-effect rounded-2xl p-6 shadow-pink-md">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-xl font-bold text-pink-600 flex items-center gap-2">
          <span>📅</span>
          <span>全部日程</span>
        </h3>
        <div class="flex gap-2">
          <n-button type="primary" size="small" class="rounded-xl" @click="handleAddSchedule">
            + 添加
          </n-button>
          <n-button text class="text-pink-500" @click="goToSchedule">
            管理 →
          </n-button>
        </div>
      </div>

      <!-- 日期选择器 -->
      <div class="mb-4">
        <n-date-picker
          v-model:value="selectedDate"
          type="date"
          class="w-full"
          placeholder="选择日期查看日程"
          clearable
        />
      </div>

      <div v-if="schedules.length > 0" class="space-y-3">
        <div
          v-for="schedule in schedules"
          :key="schedule.id"
          class="bg-white/50 rounded-xl p-4 flex items-start gap-3"
        >
          <div class="flex-shrink-0">
            <span class="text-2xl">{{ schedule.icon }}</span>
          </div>
          <div class="flex-1">
            <p class="text-pink-600 font-medium">{{ schedule.title }}</p>
            <p class="text-sm text-pink-400 mt-1">{{ schedule.date }}</p>
          </div>
          <div class="flex items-center gap-2">
            <n-checkbox v-model:checked="schedule.completed" />
            <n-button size="tiny" tertiary @click="handleEditSchedule(schedule)">
              编辑
            </n-button>
            <n-button size="tiny" tertiary type="error" @click="handleDeleteSchedule(schedule.id)">
              删除
            </n-button>
          </div>
        </div>
      </div>

      <div v-else class="text-center py-8 text-pink-300">
        <p class="text-4xl mb-2">🎉</p>
        <p>暂无日程安排</p>
      </div>
    </div>

    <!-- 添加/编辑日程模态框 -->
    <n-modal v-model:show="showScheduleModal">
      <div class="glass-effect rounded-3xl p-8 max-w-md w-full shadow-pink-xl">
        <h3 class="text-2xl font-bold text-pink-600 mb-6">
          {{ scheduleForm.id ? '编辑日程' : '添加日程' }}
        </h3>
        <n-form ref="scheduleFormRef" :model="scheduleForm" :rules="scheduleRules">
          <n-form-item label="日程标题" path="title">
            <n-input v-model:value="scheduleForm.title" placeholder="输入日程标题" />
          </n-form-item>
          <n-form-item label="日期" path="date">
            <n-date-picker
              v-model:value="scheduleForm.dateValue"
              type="date"
              class="w-full"
              placeholder="选择日期"
            />
          </n-form-item>
          <n-form-item label="图标">
            <div class="flex gap-2 flex-wrap">
              <span
                v-for="emoji in scheduleEmojis"
                :key="emoji"
                class="text-2xl cursor-pointer hover:scale-125 transition-all"
                :class="scheduleForm.icon === emoji ? 'scale-125' : ''"
                @click="scheduleForm.icon = emoji"
              >
                {{ emoji }}
              </span>
            </div>
          </n-form-item>
          <div class="flex gap-3">
            <n-button type="primary" size="large" block class="rounded-xl" @click="handleSaveSchedule">
              {{ scheduleForm.id ? '保存' : '添加' }}
            </n-button>
            <n-button size="large" block class="rounded-xl" @click="showScheduleModal = false">
              取消
            </n-button>
          </div>
        </n-form>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage, useDialog, type FormInst, type FormRules } from 'naive-ui'
import { useAuthStore } from '@/stores/auth'
import type { Schedule } from '@/types/schedule'
import type { Countdown } from '@/types/countdown'
import type { RelationshipStat } from '@/types/relationship'
import * as scheduleApi from '@/api/schedule'
import * as countdownApi from '@/api/countdown'
import * as relationshipApi from '@/api/relationship'

const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const authStore = useAuthStore()

// 加载状态
const loading = ref(false)

// 原始数据
const countdownData = ref<Countdown | null>(null)
const relationshipStatData = ref<RelationshipStat | null>(null)
const schedulesData = ref<Schedule[]>([])

// 倒计时定时器
let countdownTimer: number | null = null

// 计算倒计时显示数据
const countdown = computed(() => {
  if (!countdownData.value) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      targetDate: '',
      description: '暂无倒计时',
    }
  }

  const now = new Date().getTime()
  const target = new Date(countdownData.value.target_date).getTime()
  const diff = target - now

  if (diff <= 0) {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      targetDate: countdownData.value.target_date.split('T')[0],
      description: countdownData.value.description || countdownData.value.title,
    }
  }

  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

  return {
    days,
    hours,
    minutes,
    targetDate: countdownData.value.target_date.split('T')[0],
    description: countdownData.value.description || countdownData.value.title,
  }
})

// 计算恋爱统计数据
const stats = computed(() => {
  if (!relationshipStatData.value) {
    return {
      days: 0,
      meetings: 0,
      messages: 0,
    }
  }

  const now = new Date().getTime()
  const togetherSince = new Date(relationshipStatData.value.together_since).getTime()
  const days = Math.floor((now - togetherSince) / (1000 * 60 * 60 * 24))

  return {
    days,
    meetings: relationshipStatData.value.meet_count,
    messages: 0, // 互动次数暂时没有对应字段
  }
})

// 选中的日期
const selectedDate = ref<number | null>(null)

// 根据分类映射图标
const getCategoryIcon = (category: string): string => {
  const iconMap: Record<string, string> = {
    约会: '💖',
    工作: '💼',
    纪念日: '🎂',
    其他: '📅',
  }
  return iconMap[category] || '📅'
}

// 转换后端日程数据为前端展示格式
const schedules = computed(() => {
  return schedulesData.value.map((schedule) => ({
    id: schedule.id,
    icon: getCategoryIcon(schedule.category),
    title: schedule.title,
    date: schedule.deadline.split('T')[0],
    completed: schedule.status === '已完成',
    // 保留原始数据用于编辑
    _raw: schedule,
  }))
})

// 日程表单相关
const showScheduleModal = ref(false)
const scheduleFormRef = ref<FormInst | null>(null)
const scheduleForm = ref({
  id: null as number | null,
  title: '',
  dateValue: null as number | null,
  icon: '📅',
  category: '其他',
})

const scheduleEmojis = ['📅', '💖', '📞', '🎁', '🎂', '💼', '🎉', '✈️', '🍰', '🎡']

// 图标到分类的映射
const getIconCategory = (icon: string): string => {
  const categoryMap: Record<string, string> = {
    '💖': '约会',
    '📞': '约会',
    '💼': '工作',
    '🎂': '纪念日',
    '🎁': '纪念日',
  }
  return categoryMap[icon] || '其他'
}

const scheduleRules: FormRules = {
  title: [{ required: true, message: '请输入日程标题', trigger: 'blur' }],
  dateValue: [{ required: true, message: '请选择日期', trigger: 'blur', type: 'number' }],
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 并行加载所有数据
    const [countdowns, relationshipStats, schedulesList] = await Promise.all([
      countdownApi.getCountdowns(),
      relationshipApi.getRelationshipStats(),
      scheduleApi.getSchedules(),
    ])

    // 获取第一个"见面"类型的倒计时，如果没有则取第一个
    countdownData.value =
      countdowns.find((c: Countdown) => c.type === '见面') || countdowns[0] || null

    // 获取第一个恋爱统计记录
    relationshipStatData.value = relationshipStats[0] || null

    // 保存日程列表
    schedulesData.value = schedulesList
  } catch (error: any) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 添加日程
const handleAddSchedule = () => {
  scheduleForm.value = {
    id: null,
    title: '',
    dateValue: null,
    icon: '📅',
    category: '其他',
  }
  showScheduleModal.value = true
}

// 编辑日程
const handleEditSchedule = (schedule: any) => {
  const rawSchedule = schedule._raw as Schedule
  scheduleForm.value = {
    id: schedule.id,
    title: schedule.title,
    dateValue: new Date(rawSchedule.deadline).getTime(),
    icon: schedule.icon,
    category: rawSchedule.category,
  }
  showScheduleModal.value = true
}

// 保存日程
const handleSaveSchedule = async () => {
  if (!scheduleFormRef.value) return

  try {
    await scheduleFormRef.value.validate()

    const userId = authStore.userInfo?.id
    if (!userId) {
      message.error('请先登录')
      return
    }

    // 格式化日期为后端要求的格式 "2006-01-02 15:04:05"
    const date = new Date(scheduleForm.value.dateValue!)
    const deadline = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} 00:00:00`

    // 根据图标确定分类
    const category = getIconCategory(scheduleForm.value.icon)

    if (scheduleForm.value.id) {
      // 编辑
      await scheduleApi.updateSchedule(scheduleForm.value.id, {
        title: scheduleForm.value.title,
        deadline,
        category,
      })
      message.success('日程更新成功')
    } else {
      // 新增
      await scheduleApi.createSchedule({
        title: scheduleForm.value.title,
        deadline,
        category,
        creator_id: userId,
      })
      message.success('日程添加成功')
    }

    showScheduleModal.value = false
    // 重新加载日程列表
    await loadData()
  } catch (error: any) {
    console.error('保存日程失败:', error)
  }
}

// 删除日程
const handleDeleteSchedule = (id: number) => {
  dialog.warning({
    title: '确认删除',
    content: '确定要删除这个日程吗？',
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await scheduleApi.deleteSchedule(id)
        message.success('日程已删除')
        // 重新加载日程列表
        await loadData()
      } catch (error: any) {
        console.error('删除日程失败:', error)
        message.error('删除失败')
      }
    },
  })
}

// 跳转到日程页面
const goToSchedule = () => {
  router.push({ name: 'schedule' })
}

// 启动倒计时定时器
const startCountdownTimer = () => {
  // 每分钟更新一次倒计时
  countdownTimer = window.setInterval(() => {
    // 强制重新计算 computed
    countdownData.value = { ...countdownData.value! }
  }, 60000)
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadData()
  startCountdownTimer()
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>
